package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: fcyisxt
 * @Date: 2021/4/30 15:36
 */
@Component
public class LoginFilter extends ZuulFilter {

    /**
     * 过滤器类型：pre,routing,post,error
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 位置顺序号，zuul前置过滤器默认有5个
     * @return
     */
    @Override
    public int filterOrder() {
        return 6;
    }

    /**
     * 判断针对当前请求是否需要执行过滤代码
     * @return
     */
    @Override
    public boolean shouldFilter() {
        /*
        调用item-service 需要检查权限
        调用其他服务不判断权限，可以直接访问
         */

        //获取当前请求调用的服务id
        RequestContext cxt =RequestContext.getCurrentContext();
        String serviceId =(String) cxt.get(FilterConstants.SERVICE_ID_KEY);
        //判断id是不是"item-service"
        return "item-service".equalsIgnoreCase(serviceId);
    }

    /**
     * 过滤代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        // 得到request对象
        RequestContext cxt =RequestContext.getCurrentContext();
        HttpServletRequest request =cxt.getRequest();

        // 用request接收token参数
        String token =request.getParameter("token");

        // 如果收不到token，阻止向后台服务转发,直接向客户端返回响应
        if (StringUtils.isBlank(token)){
            cxt.setSendZuulResponse(false);

            // 向客户端直接发送响应：JsonResult ={code:400,msg:"not longin",data}
            String json =
            JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("Not Login!未登录")
                    .toString();
            // http协议头属性：Content-Type:application/json;charset=UTF-8
            cxt.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            cxt.setResponseBody(json);
        }
        return null;
    }
}